package thread_try;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyExecutors {

    // 相当于：public synchronized void func (){}
    public  void func1() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        }
    }

    // 同步类
    public void func2(){
        synchronized (MyRunnable.class){
            for (int i = 0; i <6; i++) {
                System.out.print(i+" ");
            }
        }
    }

    // 同步静态方法：
    public synchronized static Thread func3(){
        return new Thread(()->{
            for (int i=0;i<5;i++){
                System.out.println(Thread.currentThread());
            }
        });
    }

    // reentrantLock
    private final Lock lock = new ReentrantLock();

    public void func4() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        } finally {
            lock.unlock(); // 确保释放锁，从而避免发生死锁。
        }
    }

    public static void main(String[] args) {
        // CachedThreadPool：一个任务创建一个线程；
        ExecutorService executorService1 = Executors.newCachedThreadPool();

        for (int j = 0; j < 10; j++) {
                executorService1.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " is CachedThreadPool task.");
                });
        }

//        // 调用同一个被锁的
        MyExecutors el = new MyExecutors();
        executorService1.execute(el::func1);
        executorService1.execute(el::func1);

//        // 调用不同被锁的
        MyExecutors ek = new MyExecutors();
        executorService1.execute(el::func1);
        executorService1.execute(ek::func1);

        // 测试静态方法的
        executorService1.execute(func3());

        // 测试reentrant
        executorService1.execute(el::func4);
        executorService1.shutdown();

        // FixedThreadPool 允许你创建一个具有固定数量线程的线程池。
        ExecutorService executorService2 = Executors.newFixedThreadPool(2);

        for (int i = 0; i < 10; i++) {
            executorService2.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " is FixedThreadPool task.");
            });
        }

        // 测试静态方法的synchronized
        executorService2.execute(func3());

        // 测试reentrant
        executorService2.execute(ek::func4);
        executorService2.shutdown();


        // SingleThreadExecutor 是一个单线程的线程池，它确保所有的任务都在一个单独的线程中按顺序执行。
        ExecutorService executorService3 = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 10; i++) {
            executorService3.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " is SingleThreadExecutor task.");
            });
        }

        executorService3.shutdown();
    }
}
